import React, { useEffect, useState } from 'react';
import { NetworkStatus } from '@apollo/client';
import {
  Box,
  ChannelCard,
  Grid,
  GridItem,
  LinkCard,
  ListBase,
  makeToast,
  Modal,
  Text,
} from '@nova-hf/ui';
import ContractsHeader from 'beta/components/contracts-header/ContractsHeader';
import { ErrorBanner } from 'beta/components/error/ErrorBanner';
import { Cancel } from 'beta/containers/cancel/cancel';
import Payments from 'beta/store/payment';
import { formatDate, makeDate } from 'beta/utils/helpers';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import {
  useCancelSubscriptionMutation,
  useChannelsQuery,
  useContractsQuery,
  useEventsQuery,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

type TvServiceContainerProps = {
  payments?: Payments;
};

const TvServiceContainer = ({ payments }: TvServiceContainerProps) => {
  const { t } = useTranslation('containers');
  const router = useRouter();
  const serviceId = typeof router?.query?.serviceId === 'string' ? router?.query?.serviceId : '';
  const customerId = typeof router?.query?.customerId === 'string' ? router?.query?.customerId : '';
  const { data, loading, error, refetch, networkStatus } = useContractsQuery({
    variables: {
      input: {
        serviceId,
        customerId,
      },
    },
    skip: !serviceId || !customerId,
  });
  const { data: contentfulData } = useChannelsQuery({});
  const { data: eventData } = useEventsQuery({});
  const contracts = data?.contracts?.contracts;
  const backupImage =
    'https://images.ctfassets.net/kxlikh41rnjc/Po7NGxwNJjJJ4WZXKe5ig/a462cea509207f2f566ef6f52d5ffa4f/NovaTvLogo.png';

  if (!data || error || !contracts) {
    return (
      <>
        {loading && <ContractsHeader title={t('service:invoice.loading')} />}
        <ErrorBanner
          eyebrowTexts={[
            t('errors:contractList.novatv.eyebrows.1'),
            t('errors:contractList.novatv.eyebrows.2'),
            t('errors:contractList.novatv.eyebrows.3'),
          ]}
          titles={[
            t('errors:contractList.novatv.titles.1'),
            t('errors:contractList.novatv.titles.2'),
            t('errors:contractList.novatv.titles.3'),
          ]}
          descriptions={[
            t('errors:contractList.novatv.descriptions.1'),
            t('errors:contractList.novatv.descriptions.2'),
            t('errors:contractList.novatv.descriptions.3'),
          ]}
          icon="zap"
          color="pink"
          showLoading={loading || networkStatus === NetworkStatus.refetch}
          refetchButton={{
            text: t('errors:buttons.refresh'),
            icon: 'refresh',
            onClick: () => refetch(),
          }}
          loadingComponent={
            <>
              <ListBase isLoading gap={3} />
              <ListBase isLoading gap={3} />
              <ListBase isLoading />
            </>
          }
        />
      </>
    );
  }

  const today = new Date();
  const channels = contracts?.filter(
    (channel) => channel?.variant?.__typename === 'ProvisionedSubscriptionVariant',
  );
  const events = contracts?.filter(
    (event) => event?.variant?.__typename !== 'ProvisionedSubscriptionVariant',
  );
  const [showModal, setShowModal] = useState(false);
  const [cardId, setCardId] = useState('');
  const [validUntil, setValidUntil] = useState(today);
  const [cancelSubscription] = useCancelSubscriptionMutation(); //This needs to be replaced with uppsögn for store v2

  const cancel = async () => {
    try {
      const res = await cancelSubscription({
        variables: {
          input: {
            subscriptionId: cardId,
            reason: '',
          },
        },
      });
      if (res.data?.cancelSubscription?.error) {
        makeToast.danger(t('tv.error'), res.data.cancelSubscription.error.message);
      } else {
        makeToast.success(t('tv.success'), '');

        router
          .push(`/beta/${router.query.customerId}/thjonustur/${router.query.serviceId}`)
          .then(() => window.scrollTo(0, 0));
      }
    } catch (e) {
      makeToast.danger(t('tv.error'), '');
    }
  };

  const close = () => {
    setShowModal(false);
  };

  const addMonth = (date: string) => {
    const newDate = makeDate(date);
    return new Date(newDate.setMonth(newDate.getMonth() + 1));
  };

  const onClick = (id: string, validUntil: Date) => {
    setShowModal(true);
    setCardId(id);
    setValidUntil(validUntil);
  };

  const onPaymentChange = (name: string, id: string) => {
    if (payments) {
      payments.itemName = name;
      payments.contractId = id;
      router.push(
        `/beta/${router.query.customerId}/thjonustur/${router.query.serviceId}/greidslumati`,
      );
    }
  };

  const getContentfulImage = (CfItem: string, isChannel: boolean) => {
    if (isChannel) {
      const item = contentfulData?.planCollection?.items.filter((stod) =>
        stod?.product?.title?.includes(CfItem),
      );
      const info = item ? item[0] : undefined;
      return info?.product?.image?.url ? info.product.image.url : backupImage;
    } else {
      const item = eventData?.payPerViewEventCollection?.items.filter(
        (event) => event?.eventId === CfItem,
      );
      const info = item ? item[0] : undefined;
      return info?.image?.url ? info.image.url : backupImage;
    }
  };

  useEffect(() => {
    refetch();
  }, []);

  return (
    <Box display="flex" flexDirection="column">
      <Modal
        ariaLabel="uppsogn"
        onVisibilityChange={(isVisible) => setShowModal(isVisible)}
        isVisible={showModal}
      >
        <Cancel validUntil={validUntil} cancel={cancel} decline={close} />
      </Modal>
      {channels && (
        <Box>
          <Text variant="h6" marginBottom={4}>
            {t('tv.subscriptions')}
          </Text>
          <Grid gridTemplate={{ sm: 1, md: 2 }} columnGap={3} rowGap={3}>
            {channels.map((channel) => {
              return (
                <>
                  {channel?.status === 'Active' && (
                    <GridItem key={channel?.id}>
                      <ChannelCard
                        description={t('tv.renewal')}
                        validUntil={
                          channel?.latestPeriodEnd
                            ? formatDate(addMonth(channel.latestPeriodEnd), 'dd.MM.yyyy')
                            : t('tv.unlimited')
                        }
                        title={channel.variant?.name ?? t('tv.subscription')}
                        price={
                          channel?.variant?.__typename === 'Variant' ||
                          channel?.variant?.__typename === 'ProvisionedSubscriptionVariant'
                            ? channel?.variant?.monthlyCharge
                            : 0
                        }
                        cc={
                          channel?.paymentMethod?.__typename === 'CreditCardPaymentMethod' &&
                          channel.paymentMethod.maskedNumber
                            ? channel.paymentMethod.maskedNumber.slice(-8)
                            : t('tv.bankClaim')
                        }
                        paymentText={t('tv.paymentMethod')}
                        imageSrc={
                          channel?.variant?.id
                            ? getContentfulImage(channel.variant.name ?? '', true)
                            : 'https://images.ctfassets.net/kxlikh41rnjc/Po7NGxwNJjJJ4WZXKe5ig/a462cea509207f2f566ef6f52d5ffa4f/NovaTvLogo.png'
                        }
                        unit={t('tv.perMonth')}
                        menuItems={[
                          {
                            text: t('tv.tryAgain'),
                            onClick: () => alert('Coming Soon'),
                          },
                          {
                            text: t('tv.change'),
                            onClick: () =>
                              onPaymentChange(
                                channel?.variant?.name ? channel.variant.name : '',
                                channel?.id ? channel.id : '',
                              ),
                          },
                          {
                            text: t('tv.cancel'),
                            onClick: () =>
                              onClick(
                                channel?.id,
                                addMonth(channel?.latestPeriodEnd ? channel.latestPeriodEnd : ''),
                              ),
                          },
                        ]}
                      />
                    </GridItem>
                  )}
                </>
              );
            })}
          </Grid>
        </Box>
      )}
      {events && (
        <Box>
          <Text variant="h6" marginBottom={4} marginTop={10}>
            {t('tv.events')}
          </Text>
          <Grid gridTemplate={{ sm: 1, md: 2 }} columnGap={3} rowGap={3}>
            {events?.map((event) => {
              return (
                <GridItem key={event?.id}>
                  <LinkCard
                    eyebrow={t('tv.stream')}
                    highlight={
                      event?.variant?.__typename === 'Variant' ||
                      event?.variant?.__typename === 'SubscriptionVariant'
                        ? event?.variant?.startDate
                          ? formatDate(event.variant.startDate, 'dd.MM.yyyy - HH:mm')
                          : t('dateUnknown')
                        : t('noDate')
                    }
                    image={{
                      alt: 'ticket',
                      url: event?.variant?.id
                        ? getContentfulImage(event.variant.id, false)
                        : 'https://images.ctfassets.net/kxlikh41rnjc/Po7NGxwNJjJJ4WZXKe5ig/a462cea509207f2f566ef6f52d5ffa4f/NovaTvLogo.png',
                    }}
                    mainButton={{
                      renderAs: 'a',
                      colorScheme: 'white',
                      dottedShadow: 'none',
                      icon: 'longArrowRight',
                      text: t('tv.ticket'),
                      href: 'https://www.novatv.is/page/vidburdir',
                    }}
                    title={event?.variant?.name ?? ''}
                  />
                </GridItem>
              );
            })}
          </Grid>
        </Box>
      )}
    </Box>
  );
};

export default inject('payments')(observer(TvServiceContainer));
